package com.example.launibleplugin.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.material3.HorizontalDivider
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.launibleplugin.protocol.AxDateMessage
import com.example.launibleplugin.protocol.AxFvcMessage
import com.example.launibleplugin.protocol.ProtocolMessage

/**
 * 测量数据展示组件
 * Function: 展示呼吸家设备返回的测量数据
 * Note: 支持显示日期时间数据和FVC测量数据
 */
@Composable
fun MeasurementDataDisplayComponent(
    measurementData: List<ProtocolMessage>,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .padding(16.dp),
        shape = RoundedCornerShape(12.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Text(
                text = "测量数据",
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.primary,
                modifier = Modifier.padding(bottom = 16.dp)
            )
            
            if (measurementData.isEmpty()) {
                Text(
                    text = "暂无测量数据",
                    fontSize = 16.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.fillMaxWidth()
                )
            } else {
                measurementData.forEach { data ->
                    when (data) {
                        is AxDateMessage -> {
                            DateTimeDataCard(data)
                        }
                        is AxFvcMessage -> {
                            FvcDataCard(data)
                        }
                        else -> {
                            // 其他类型的数据可以在这里处理
                        }
                    }
                    Spacer(modifier = Modifier.height(12.dp))
                }
            }
        }
    }
}

/**
 * 日期时间数据卡片
 */
@Composable
fun DateTimeDataCard(data: AxDateMessage) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(8.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f)
        )
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp)
        ) {
            Text(
                text = "📅 日期时间数据",
                fontSize = 16.sp,
                fontWeight = FontWeight.SemiBold,
                color = MaterialTheme.colorScheme.primary,
                modifier = Modifier.padding(bottom = 8.dp)
            )
            
            DataRow("时间数据", data.timeData)
            DataRow("参数1", data.param1.toString())
            DataRow("参数2", data.param2.toString())
            DataRow("参数3", data.param3.toString())
            if (data.checksum.isNotEmpty()) {
                DataRow("校验码", data.checksum)
            }
        }
    }
}

/**
 * FVC测量数据卡片
 */
@Composable
fun FvcDataCard(data: AxFvcMessage) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(8.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.3f)
        )
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp)
        ) {
            Text(
                text = "🫁 FVC测量数据",
                fontSize = 16.sp,
                fontWeight = FontWeight.SemiBold,
                color = MaterialTheme.colorScheme.primary,
                modifier = Modifier.padding(bottom = 8.dp)
            )
            
            // 基本信息
            Text(
                text = "基本信息",
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.onSurface,
                modifier = Modifier.padding(vertical = 4.dp)
            )
            DataRow("测试编号", data.testNumber.toString())
            DataRow("测试次数", data.testCount.toString())
            DataRow("测试质量", getTestQualityText(data.testQuality))
            
            HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))
            
            // 肺功能指标
            Text(
                text = "肺功能指标",
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.onSurface,
                modifier = Modifier.padding(vertical = 4.dp)
            )
            DataRow("PEF (呼气峰流速)", "${String.format("%.2f", data.pef)} L/min")
            DataRow("FEV1 (第一秒用力呼气量)", "${String.format("%.2f", data.fev1)} L")
            DataRow("FEV0.25 (0.25秒用力呼气量)", "${String.format("%.2f", data.fev025)} L")
            DataRow("FVC (用力肺活量)", "${String.format("%.2f", data.fvc)} L")
            DataRow("FEV1/FVC比值", "${String.format("%.2f", data.fev1_fvc)}")
            DataRow("FET (用力呼气时间)", "${String.format("%.2f", data.fet)} s")
            
            HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))
            
            // 流速指标
            Text(
                text = "流速指标",
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.onSurface,
                modifier = Modifier.padding(vertical = 4.dp)
            )
            DataRow("MEF75", "${String.format("%.2f", data.mef75)} L/s")
            DataRow("MEF50", "${String.format("%.2f", data.mef50)} L/s")
            DataRow("MEF25", "${String.format("%.2f", data.mef25)} L/s")
            DataRow("MMEF (平均最大呼气流速)", "${String.format("%.2f", data.mmef)} L/s")
            
            HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))
            
            // 环境和生理指标
            Text(
                text = "环境和生理指标",
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.onSurface,
                modifier = Modifier.padding(vertical = 4.dp)
            )
            DataRow("温度", "${String.format("%.1f", data.temperature)}°C")
            DataRow("气压", "${data.pressure} hPa")
            DataRow("湿度", "${data.humidity}%")
            DataRow("心率", "${data.heartRate} bpm")
            DataRow("血氧饱和度", "${data.oxygenSaturation}%")
            
            if (data.checksum.isNotEmpty()) {
                HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))
                DataRow("校验码", data.checksum)
            }
        }
    }
}

/**
 * 数据行组件
 */
@Composable
fun DataRow(label: String, value: String) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 2.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = label,
            fontSize = 13.sp,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            modifier = Modifier.weight(1f)
        )
        Text(
            text = value,
            fontSize = 13.sp,
            fontWeight = FontWeight.Medium,
            color = MaterialTheme.colorScheme.onSurface,
            textAlign = TextAlign.End,
            modifier = Modifier.weight(1f)
        )
    }
}

/**
 * 获取测试质量文本
 */
fun getTestQualityText(quality: Int): String {
    return when (quality) {
        0 -> "未知"
        1 -> "优秀"
        2 -> "良好"
        3 -> "一般"
        4 -> "较差"
        else -> "未定义($quality)"
    }
}